using System;
using DDA;
using UnityEngine;
using UnityEngine.UI;
using QFramework;

namespace Survivor
{
	public class UIGamePanelData : UIPanelData
	{
	}
	public partial class UIGamePanel : UIPanel
	{
		protected override void OnInit(IUIData uiData = null)
		{
			mData = uiData as UIGamePanelData ?? new UIGamePanelData();
			// 时间显示
			Global.CurrentTime.RegisterWithInitValue((value) =>
			{
				if (Time.frameCount % 30 == 0)  // 每30帧更新一次 
				{
					var curSecondsInt = Convert.ToInt32(value);
					var seconds = curSecondsInt % 60;
					var minutes = curSecondsInt / 60;
					TextTime.text = $"AliveTime:{minutes:00}:{seconds:00}";
				}
			}).UnRegisterWhenGameObjectDestroyed(gameObject);

			ActionKit.OnUpdate.Register(() =>
			{
				Global.CurrentTime.Value += Time.deltaTime;
				if (Global.CurrentTime.Value >= Global.GameWinAliveTime)
				{
					if (EnemyGenerator.EnemyNum.Value ==0)	
					{
						UIKit.OpenPanel<UIGameWinPanel>();
					}
				}
			}).UnRegisterWhenGameObjectDestroyed(gameObject);

			// 更新经验文本
			Global.Exp.RegisterWithInitValue((value) =>
			{
				ExpValue.fillAmount = value/(float)Global.ExpToNextLevel();
			}).UnRegisterWhenGameObjectDestroyed(gameObject);
			// 更新等级文本
			Global.Level.RegisterWithInitValue((value) =>
			{
				TextLevel.text = "Level:" + value;
			}).UnRegisterWhenGameObjectDestroyed(gameObject);
			
			// 更新怪物数量文本
			EnemyGenerator.EnemyNum.RegisterWithInitValue((value) =>
			{
				TextEnemyNum.text = "EnemyNum:" + value;
			}).UnRegisterWhenGameObjectDestroyed(gameObject);
			
			// 更新金币数量文本
			Global.Coin.RegisterWithInitValue((value) =>
			{
				TextCoins.text = "Coins:" + value;
			}).UnRegisterWhenGameObjectDestroyed(gameObject);
			
			// 升级逻辑
			Global.Exp.RegisterWithInitValue((value) =>
			{
				if (value >= Global.ExpToNextLevel())
				{
					ExpUpgradePanel.Show();
				}

			}).UnRegisterWhenGameObjectDestroyed(gameObject);
			ExpUpgradePanel.Hide();
			
			//DDA
			ButtonStartDDA.onClick.AddListener(()=>
			{
				ButtonStartDDA.enabled = false;
				DDAParser.Instance.LoadTree();
			});
			
			ButtonShowLog.onClick.AddListener(LogPanel.Show);
		}
		
		protected override void OnOpen(IUIData uiData = null)
		{
		}
		
		protected override void OnShow()
		{
		}
		
		protected override void OnHide()
		{
		}
		
		protected override void OnClose()
		{
		}
	}
}
